package com.iflytek.uoamp.agent.monitor.find;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import java.util.concurrent.CountDownLatch;

import org.apache.log4j.Logger;

import com.iflytek.uoamp.agent.monitor.mcagent.CommonConstant;


public class CMDExecutorWorkerJob implements Runnable{
	private final String cmd;
	private final List<String> result;
	private final CountDownLatch endSignal;
	private final Process ps;
	private final int type;
	public CMDExecutorWorkerJob(CountDownLatch endSignal, Process ps, String cmd, List<String> result) {
		this(endSignal, ps, cmd, result, 0);
	}
	public CMDExecutorWorkerJob(CountDownLatch endSignal, Process ps, String cmd, List<String> result, int type) {
		this.endSignal = endSignal;
		this.ps = ps;
		this.cmd = cmd;
		this.result = result;
		this.type = type;
	}

	@Override
	public void run() {
		BufferedReader bufferedReader = null;
		try {
			// 获取错误输出  
			InputStream inputStream = null;
			if (0 == this.type) {
				inputStream = this.ps.getInputStream();
			} else {
				inputStream = this.ps.getErrorStream();
			}
			
			InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
			bufferedReader = new BufferedReader(inputStreamReader);
			// 读取标准输出
			String s = null;
			while((s = bufferedReader.readLine()) != null){
				result.add(s.concat(CommonConstant.ComponentMCAgent.RESULTOUTPUT_SHELL_SPLIT));
			}
		} catch (Exception exception) {
			Logger.getRootLogger().error(exception.getMessage());
		} finally {
			if (null != bufferedReader) {
				try {
					bufferedReader.close();
				} catch (Exception exc) {
					Logger.getRootLogger().error(exc.getMessage());
				}
			}
			endSignal.countDown();
		}
		// 任务执行完成
		Logger.getRootLogger().info(Thread.currentThread().getName() + " execute completed, cmd = " + cmd);
	}
}
